package matchers;

import org.apache.commons.io.FileUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.internal.matchers.TypeSafeMatcher;

import java.io.File;
import java.io.IOException;

/**
 * User: user
 * Date: 22/10/11
 * Time: 13:17
 */
public class FileMatchers {

    public static Matcher<File> contentEqualsTo(final File expectedLogFile) {
        return new TypeSafeMatcher<File>() {

            String fileTested;
            String fileExpected;

            @Override
            public boolean matchesSafely(File file) {
                try {
                    fileTested = FileUtils.readFileToString(file);
                } catch (IOException e) {
                    throw new RuntimeException("no such file " + file.getName());
                }
                try {
                    fileExpected = FileUtils.readFileToString(expectedLogFile);
                } catch (IOException e) {
                    throw new RuntimeException("no such file " + file.getName());
                }
                return fileTested.equals(fileExpected);
            }

            public void describeTo(Description description) {
                description.appendValue(fileTested);
            }
        };
    }

    public static Matcher<File> isExists() {
        return new TypeSafeMatcher<File>() {

            File testFile;

            @Override
            public boolean matchesSafely(File file) {
                testFile = file;
                return file.exists();
            }

            public void describeTo(Description description) {
                description.appendText("file doesn't exists ");
                description.appendValue(testFile.getName());
            }
        };
    }

    public static Matcher<File> containsText(final String fileText) {
        return new TypeSafeMatcher<File>() {

            String actualContent;

            @Override
            public boolean matchesSafely(File file) {
                try {
                    actualContent = FileUtils.readFileToString(file);
                    return actualContent.equals(fileText);
                } catch (IOException e) {
                    throw new RuntimeException("File not found " + file.getName());
                }
            }

            public void describeTo(Description description) {
                description.appendValue(fileText);
                description.appendText("\n     got: ");
                description.appendValue(actualContent);
            }
        };
    }

}
